package com.todod.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.todod.common.util.TododDate;
import com.todod.dto.FeaturDto;
import com.todod.entity.QueryEntry;
import com.todod.entity.ResultData;
import com.todod.model.Featur;
import com.todod.service.FeatureService;

/**
 * 新特性
 * 
 * @author 金鹏飞
 *
 */
@RestController
@RequestMapping("/feature")
public class FeatureController {
	@Autowired
	private FeatureService service;
	Logger log = LoggerFactory.getLogger(FeatureController.class);

	/**
	 * 新特性的删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/del")
	public ResultData del(Long id) {
		service.del(id);
		return ResultData.success();
	}

	/**
	 * 新特性保存
	 * 
	 * @param _userId
	 * @param featur
	 * @return
	 */
	@RequestMapping("/save")
	public ResultData save(@RequestAttribute Long _userId, @RequestBody Featur featur) {
		Featur featur2 = service.selectByname(featur.getName());
		if (featur2 != null) {
			return ResultData.error(ResultData.ESTIMATE_ERROR_CODE, "名称已存在");
		}
		featur.setCreateTime(LocalDateTime.now());
		featur.setCreateUserId(_userId);
		log.info("保存", featur);
		service.save(featur);
		return ResultData.success();
	}

	/**
	 * 新特性编辑
	 * 
	 * @param featur
	 * @param _userId
	 * @return
	 */
	@RequestMapping("/editCon")
	public ResultData update(@RequestBody Featur featur, @RequestAttribute Long _userId) {
		log.debug("修改", featur);
		featur.setModifyUserId(_userId);
		featur.setModifyTime(LocalDateTime.now());
		service.update(featur);
		return ResultData.success();
	}

	/**
	 * 新特性获取列表
	 * 
	 * @param _userId
	 * @param entry
	 * @return
	 */

	@RequestMapping("/getList1")
	public ResultData getList1() {
		List<Featur> list = service.getList1();
		return ResultData.success("ok", list);
	}

	/**
	 * 新特性获取列表并且进行分页
	 * 
	 * @param _userId
	 * @param entry
	 * @return
	 */
	@RequestMapping("/getList")
	public ResultData getList(@RequestAttribute Long _userId, @RequestBody QueryEntry entry) {
		log.debug("entry输出", entry);
		IPage<FeaturDto> page = service.getList(entry);
		return ResultData.success("ok", page);
	}

	@Value("${file.upload.path}")
	private String uploadPath;// 上传路径
	@Value("${file.upload.mapping}")
	private String showPath; // 映射路径
	@Value("${file.visit}")
	private String visi;

	/**
	 * 新特性上传图片
	 * 
	 * @param file
	 * @param req
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/upload")
	public ResultData get(@RequestParam("uploadfile_ant") MultipartFile file, HttpServletRequest req)
			throws UnsupportedEncodingException {
		String newDate = TododDate.getInstance().getSimpledate();
		req.setCharacterEncoding("utf-8");
		// 防止上传空文件导致奔溃
		if (file.isEmpty()) {
			throw new NullPointerException("文件为空");
		}
		// 设置文件上传后的路径
		String filePath = uploadPath + newDate + File.separator;

		// 获取文件名后缀名
		String originalName = file.getOriginalFilename();
		String suffix = StringUtils.substringAfterLast(originalName, ".");
		String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;

		File dest = new File(filePath + fileName);
		if (!dest.getParentFile().exists()) {
			// 假如文件不存在即重新创建新的文件已防止异常发生
			dest.getParentFile().mkdirs();
		}
		try {
			// transferTo（dest）方法将上传文件写到服务器上指定的文件
			file.transferTo(dest);
			// 保存t_upload_file表中
			String paString = visi + showPath + newDate + "/" + fileName;
			return ResultData.success("ok", paString);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.error("添加失败");
		}
	}

}
